/**
 * Created by Administrator on 2018/1/4.
 */

import {BluetoothSerial} from '@ionic-native/bluetooth-serial';
import {ZQHToast} from "./zqhToast";

export class BlueToothUtil {
  public static bluetoothSerial: BluetoothSerial;
  public static unLockcourse: any;

  constructor()
  {
    console.log('Hello BluetoothProvider Provider');
  }

  /* 字节数组转十六进制字符串 */
  public  static Bytes2Str(arr) {
    let str = "";
    for (let i = 0; i < arr.length; i++) {
      let tmp = arr[i].toString(16);
      if (tmp.length == 1) {
        tmp = "0" + tmp;
      }
      str += tmp;
    }
    return str;
  }

  /* 十六进制字符串转字节数组 */
  public  static Str2Bytes(str) {
    let pos = 0;
    let len = str.length;
    if (len % 2 != 0) {
      return null;
    }
    len /= 2;
    let hexA = [];
    for (let i = 0; i < len; i++) {
      let s = str.substr(pos, 2);
      let v = parseInt(s, 16);
      hexA.push(v);
      pos += 2;
    }
    return hexA;
  }

  /* 获取锁密码 */
  public  static getPassword(lockID: string) {
    return "9ABCE122";
  }

  /* 打开手机蓝牙设置界面 */
  public static showBluetoothSettings() {
    this.bluetoothSerial.showBluetoothSettings();
  }

  /* 清除监听后再连接 */
  public static clearDeviceDiscoveredListener() {
    this.bluetoothSerial.clear();
  }

  /* 发现配对可连接的设备 */
  public static discoverUnpaired() {
    this.bluetoothSerial.discoverUnpaired().then(
      function () {
        console.log("配对成功");
      },
      function () {
        console.log("配对失败");
      }
    );
  }

  /* 判断蓝牙是否可用 0:可用，1:不可用*/
  public static judgeEnable(callBack) {
    this.bluetoothSerial.isEnabled().then(
      function () {
        console.log("蓝牙可以正常使用！");
        callBack(0);
      },
      function () {
        console.log("蓝牙不可以正常使用！");
        callBack(1);
      }
    );
  }

  /* 判断蓝牙是否已经连接 0：代表已经连接，1：代表未连接 */
  public static judgeConnected(callback) {
    this.bluetoothSerial.isConnected().then(
      function () {
        console.log("蓝牙已经连接！");
        callback(0);
      },
      function () {
        console.log("蓝牙未连接！");
        callback(1);
      }
    );
  }

  /* 断开已连接的蓝牙设备 0：代表蓝牙断开成功，1：代表蓝牙断开失败 */
  public static disconnect(callback) {
    this.bluetoothSerial.disconnect().then(
      function () {
        console.log("蓝牙断开成功！");
        ZQHToast.showShortCenter("蓝牙已经断开!");
        callback(0);
      },
      function () {
        console.log("蓝牙断开失败！");
        callback(1);
      }
    );
  }

  /* 查看已经连接设备的信息 */
  public static setDeviceDiscoveredListener(callback) {
    this.bluetoothSerial.setDeviceDiscoveredListener().subscribe(
      function (device) {
        callback(device);
      }
    );
  }

  /* 设备连接 */
  public static connect(deviceAddress, callBack) {
    this.bluetoothSerial.connect(deviceAddress).subscribe(
      function (success) {
        console.log("设备连接成功：" + success);
        ZQHToast.showShortCenter("设备连接成功!");
        callBack(0);
      },
      function (error) {
        console.log("设备连接失败：" + error);
        callBack(1);
      }
    );
  }

  /* 数据写入串行端口 */
  public static write(data) {
    this.bluetoothSerial.write(data).then(
      function (success) {
        console.log("设备写入成功：" + success);
      },
      function (error) {
        console.log("设备写入失败：" + error);
      }
    );
  }

  /* 查看连接设备的数据回调 */
  public static subscribeRawData(callBack) {
    this.bluetoothSerial.subscribeRawData().subscribe(
      function (success) {
        callBack(success);
      },
      function (error) {
        callBack(error);
      }
    );
  }

  /*
   * 开锁步骤：
   * 1.判断蓝牙是否已经连接
   * 2.如果未连接，则判断手机蓝牙是否打开
   * 3.如果没有打开，则打开蓝牙开启界面
   * 4.如果已经打开，则进行设备连接步骤
   * */
  public static unLock() {
    let firstRead: string;
    let secondRead: string;
    let lockID: string;
    this.judgeConnected(result => {
      if (result == 1) {
        this.unLockcourse ("<<- 蓝牙未连接!");
        this.judgeEnable(result => {
          if (result == 1) {
            this.showBluetoothSettings();
          } else {
            this.setDeviceDiscoveredListener(deviceMsg => {
              console.log(deviceMsg);
              if (deviceMsg.name === "HC-06") {
                //清除监听
                this.clearDeviceDiscoveredListener();
                this.connect(deviceMsg.address, result => {
                  if (result == 0) {
                    this.unLockcourse("<<- 蓝牙已连接!");
                    this.subscribeRawData(result => {
                      let bytes = new Uint8Array(result);
                      let readStr = this.Bytes2Str(bytes);
                      if (readStr.length == 2) {
                        firstRead = readStr;
                        secondRead = "";
                      } else {
                        secondRead = readStr;
                      }
                      //代表开锁
                      if (firstRead == "55") {
                        if (secondRead.length > 0) {
                          switch (bytes[0]) {
                            //读开锁器ID和获取密码
                            case 0x02: {
                              //获取开锁器ID
                              lockID = secondRead.substring(2, 10);
                              this.unLockcourse("<<- 锁编号："+lockID);
                              let pwd = this.getPassword(lockID);
                              console.log("pwd=" + pwd);
                              //获取开锁器密码
                              let readData = this.Str2Bytes('5503' + pwd + 'AA');
                              this.write(readData);
                              break;
                            }
                            //密码正确
                            case 0x05: {
                              this.unLockcourse("<<- 开锁成功");
                              ZQHToast.showShortCenter("开锁成功！");
                              break;
                            }

                            //密码错误
                            case 0x06: {
                              this.unLockcourse("<<- 开锁密码错误");
                              ZQHToast.showShortCenter("密码错误！");
                              break;
                            }

                            //锁头已置于锁体
                            case 0x0a: {
                              this.unLockcourse("<<- 锁头已置于锁体");
                              ZQHToast.showShortCenter("锁头已置于锁体！");
                              let data = new Uint8Array(7);
                              data[0] = 0x55;
                              data[1] = 0x01;
                              data[2] = 0x00;
                              data[3] = 0x00;
                              data[4] = 0x00;
                              data[5] = 0x00;
                              data[6] = 0xaa;
                              this.write(data);
                              break;
                            }
                            //锁头已离开锁体
                            case 0x0b: {
                              this.unLockcourse("<<- 锁头已离开锁体");
                              ZQHToast.showShortCenter("锁头已离开锁体！");
                              break;
                            }

                            default:
                              break;
                          }
                        }
                      } else if (firstRead === "02") {
                        //代表读头
                      }
                    })
                  }
                });
              }
            });
            this.discoverUnpaired();
          }
        })
      }
    })
  }
}
